<?php

class set_tag_handler extends _site_handler {
	public function __construct($m, $view) {
		$this->InitializeSite($m);

		if ( !isset($_GET['back_url']) ) $_GET['back_url'] = '/';

		if ( !$this->User ) {
			header("Location: " . $this->GetUrl('login', (($this->Ajax)?'ajax=1&':'') . 'back_url=' . urlencode($this->Url)));
			exit;
		}

		if (
			!isset($_GET['action']) || !($action = $_GET['action']) ||
			!isset($_GET['id'])     || !($id     = intval($_GET['id'])) ||
			!isset($_GET['tag'])    || !($tag    = $this->GetCleanTag($_GET['tag']))
		) {
			header("Location: " . $_GET['back_url']);
			exit;
		}

		if ( $action == 'add_tag' ) {
			$query = "SELECT
							st.id,
							t.id AS tag_id
						FROM
							msnu_sgenre AS t
						LEFT OUTER JOIN
							msnu_smileysgenre AS st ON
								st.sgenre_id=t.id AND
								st.usr_id=" . $this->User->Id . " AND
								st.smiley_id=" . $id . "
						WHERE
							t.dname=\"" . mysql_escape_string($tag) . "\"
						LIMIT
							1
							";

			$result = $this->GetResult($query);

			if ( $result && ($row = mysql_fetch_assoc($result)) && $row['id'] ) {
				$query = "UPDATE msnu_smileysgenre SET enabled=1 WHERE id=" . $row['id'] . " LIMIT 1";
				$this->GetResult($query);
			} elseif ( isset($row) ) {
				$query = "INSERT INTO msnu_smileysgenre SET sgenre_id=" . $row['tag_id'] . ", usr_id=" . $this->User->Id . ", smiley_id=" . $id . ", added=NOW(), enabled=1";
				$this->GetResult($query);
			}
		} elseif ( $action == 'remove_tag' ) {
			$query = "SELECT id FROM msnu_sgenre WHERE dname=\"" . mysql_escape_string($tag) . "\" LIMIT 1";
			$result = $this->GetResult($query);

			if ( $result && ($row = mysql_fetch_assoc($result)) ) {
				$query = "UPDATE msnu_smileysgenre SET enabled=0 WHERE sgenre_id=" . $row['id'] . " AND usr_id=" . $this->User['id'] . " AND smiley_id=" . $id . " LIMIT 1";
				$this->GetResult($query);
			}
		}

		if ( !$this->Ajax ) {
			header("Location: " . $_GET['back_url']);
			exit;
		}
	}
}
